﻿using System;
using System.Collections.Generic;
using Dou.UI;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Simple
{
    public class Test_SuperLoopList : MonoBehaviour
    {
        public SuperLoopList list;

        [NonSerialized]
        public List<Test_SuperLoopList_ChatData> chatDataList = new List<Test_SuperLoopList_ChatData>();

        [NonSerialized]
        public List<string> content = new List<string>
        {
            "願意為你效勞",
            "是！那麼（玩家名稱）大人，請隨我來吧。",
            "軍師設下重重難關，謀士皆一一破解，你大喜，將其重用。",
            "寶刀成了你的私人珍藏，每當夜深人靜時，你都會取出寶刀細細觀賞，感受著它所帶來的速度與力量。",
            "你在巡視領地時，忽然聞到一股濃鬱的茶香。隨著香味的指引，你來到竹林深處。竹林間，一座竹制的茶室若隱若現，一位隱士正坐在其中煮茶。他微微一笑，邀請你一同品茶。",
        };
        
        private void Awake()
        {
            // 填充数据
            for (int i = 0; i < 100; i++)
            {
                chatDataList.Add(new Test_SuperLoopList_ChatData
                {
                    type = Random.Range(0, 2),
                    text = content[Random.Range(0, content.Count)],
                });
            }

            list.getItemNameFunc = index =>
            {
                var data = chatDataList[index];
                return data.type == 0 ? "MyChat" : "OtherChat";
            };
            list.onItemInit += (go, index) =>
            {
                var data = chatDataList[index];
                Debug.Log("Item 初始化：" + index);
            };
            list.onItemEnable += (go, index) =>
            {
                var data = chatDataList[index];
                Debug.Log("Item 生效：" + index);
            };
            list.onItemUpdate += (go, index) =>
            {
                var data = chatDataList[index];

                var text = go.transform.Find("Text").GetComponent<DTextMeshProUGUI>();
                var rect = go.GetComponent<RectTransform>();

                text.text = data.text;

                var textHeight = text.preferredHeight;
                rect.sizeDelta = new Vector2(rect.sizeDelta.x, textHeight + 70);
            };
            list.onItemDisable += (go, index) =>
            {
                Debug.Log("Item 失效：" + index);
            };
            list.count = chatDataList.Count;
        }

        public void AddChatData()
        {
            chatDataList.Add(new Test_SuperLoopList_ChatData
            {
                type = Random.Range(0, 2),
                text = content[Random.Range(0, content.Count)],
            });
            
            list.count = chatDataList.Count;
            JumpToBottom();
        }

        public void JumpToTop()
        {
            list.JumpToTop();
        }
        
        public void JumpTo50()
        {
            list.JumpToIndex(50);
        }
        
        public void JumpToBottom()
        {
            list.JumpToBottom();
        }
    }

    public class Test_SuperLoopList_ChatData
    {
        public int type; // 0 自己说的话 1 别人说的话
        public string text; // 聊天内容
    }
}
